package com.amumu.drama.common.base.mapstruct.ext;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;

/**
 * <p>
 * MapStruct映射扩展接口，处理String和xxx[]的转换（需要字段名相同，若不相同则需要后置处理）
 * <p>
 * 例: public interface xxxMapping extends BaseMapping<xxxDO, xxxDTO>, StringToAnyArrayMapping
 */
public interface StringToAnyArrayMapping {

    /** 分隔符，默认英文逗号 */
    default String getSeparatorChars() {
        return ",";
    }

    /** 数组转String的时候是否忽略Null元素，默认true */
    default boolean skipNullOnJoinString() {
        return true;
    }

    /** String转数组时候是否忽略空字符串，默认true */
    default boolean omitEmptyStringsOnSplit() {
        return true;
    }

    /** String转String[] */
    default String[] stringToStringArray(String val) {
        if (StringUtils.isBlank(val)) {
            return new String[0];
        }

        Splitter splitter = Splitter.on(getSeparatorChars()).trimResults();
        if (omitEmptyStringsOnSplit()) {
            splitter = splitter.omitEmptyStrings();
        }
        return splitter.splitToList(val).toArray(new String[0]);
    }

    /** string[]转String */
    default String stringArrayToString(String[] array) {
        if (array == null) {
            return null;
        }
        if (array.length == 0) {
            return StringUtils.EMPTY;
        }

        Joiner joiner = Joiner.on(getSeparatorChars());
        if (skipNullOnJoinString()) {
            joiner = joiner.skipNulls();
        }
        return joiner.join(array);
    }

    /** String转Long[] */
    default Long[] stringToLongArray(String val) {
        if (StringUtils.isBlank(val)) {
            return new Long[0];
        }

        Splitter splitter = Splitter.on(getSeparatorChars()).trimResults();
        if (omitEmptyStringsOnSplit()) {
            splitter = splitter.omitEmptyStrings();
        }
        return splitter.splitToStream(val).map(Long::parseLong).toArray(Long[]::new);
    }

    /** Long[]转String */
    default String longArrayToString(Long[] array) {
        if (array == null) {
            return null;
        }
        if (array.length == 0) {
            return StringUtils.EMPTY;
        }
        
        Joiner joiner = Joiner.on(getSeparatorChars());
        if (skipNullOnJoinString()) {
            joiner = joiner.skipNulls();
        }
        return joiner.join(array);
    }
}
